<template>
  <div class="option-wrapper">
    <div class="option-main">
      <a-form layout="vertical" :model="formState" :rules="rules">
        <div class="option-column">
          <div class="column-title">设备信息</div>
          <div class="column-content">
            <div class="content-item">
              <a-form-item label="设备名称" name="name">
                <a-input v-model:value="formState.name" placeholder="请输入设备名称" />
              </a-form-item>
            </div>
            <div class="content-item">
              <a-form-item label="设备序列号" name="sn">
                <a-input v-model:value="formState.sn" placeholder="请输入设备序列号" />
              </a-form-item>
            </div>
            <div class="content-item">
              <a-form-item label="保修期月数" name="warranty_month">
                <a-input-number v-model:value="formState.warranty_month" placeholder="请输入保修期月数" :min="0"
                  style="width: 100%" addon-after="个月" />
              </a-form-item>
            </div>
            <div class="content-item">
              <a-form-item label="设备型号" name="model_number">
                <a-input v-model:value="formState.model_number" placeholder="请输入设备型号" />
              </a-form-item>
            </div>
            <div class="content-item">
              <a-form-item label="设备状态" name="device_status_id">
                <a-select v-model:value="formState.device_status_id" placeholder="请选择状态" allow-clear>
                  <a-select-option v-for="(item, index) in statusOptions" :key="index" :value="item.value">{{ item.text
                  }}</a-select-option>
                </a-select>
              </a-form-item>
            </div>
            <div class="content-item">
              <a-form-item label="软件版本" name="app_version">
                <a-input v-model:value="formState.app_version" placeholder="请输入软件版本" />
              </a-form-item>
            </div>
            <div class="content-item">
              <a-form-item label="备注" name="remark">
                <a-textarea v-model:value="formState.remark" placeholder="请输入备注" :rows="3" />
              </a-form-item>
            </div>
          </div>
        </div>
        <div class="option-column">
          <div class="column-title">设备模型</div>
          <a-upload-dragger v-model:fileList="fileList1" name="file" :multiple="false" :max-count="1"
            :customRequest="customUpload1" @change="handleChange1" @drop="handleDrop1">
            <p class="ant-upload-drag-icon">
              <CloudUploadOutlined />
            </p>
            <p class="ant-upload-hint">
              将模型拖拽到此，或单击<span class="blue">直接上传</span>
            </p>
          </a-upload-dragger>
        </div>
        <div class="option-column">
          <div class="column-title">预览图片</div>
          <a-upload-dragger v-model:fileList="fileList2" name="file" :multiple="false" :max-count="1"
            :customRequest="customUpload2" @change="handleChange2" @drop="handleDrop2">
            <p class="ant-upload-drag-icon">
              <CloudUploadOutlined />
            </p>
            <p class="ant-upload-hint">
              将jpg、bmp、png格式的图片拖拽到此，或单击<span class="blue">直接上传</span>分辨建议为400*300
            </p>
          </a-upload-dragger>
        </div>
        <div class="option-column">
          <div class="column-title">仪器介绍</div>
          <edit v-model:value="formState.introduce" />
        </div>
        <div class="option-column">
          <div class="column-title">实验内容</div>
          <edit v-model:value="formState.experiments" />
        </div>
        <div class="option-column">
          <div class="column-title">配置参数</div>
          <div class="column-content" v-for="(item, index) in formState.device_param_list" :key="index">
            <div class="content-item">
              <a-form-item label="参数名称" name="param_key">
                <a-input v-model:value="item.param_key" placeholder="请输入参数名称" />
              </a-form-item>
            </div>
            <div class="content-item">
              <a-form-item label="参数值" name="param_value">
                <a-input v-model:value="item.param_value" placeholder="请输入参数值" />
              </a-form-item>
              <MinusCircleOutlined v-if="formState.device_param_list.length > 1" class="delete-button"
                @click="deleteDevice(index)" />
            </div>
          </div>
          <div class="column-footer">
            <a-button type="dashed" :icon="h(PlusOutlined)" @click="addDevice">添加配置参数</a-button>
          </div>
        </div>
        <!-- <div class="option-column">
          <div class="column-title">报修二维码</div>
          <div class="column-content">
            <p v-if="!formState.url_report_repair">创建设备后自动生成</p>
            <div v-else>
              <p>暂无二维码</p>
            </div>
          </div>
        </div> -->
        <div class="option-footer">
          <a-button class="opt-btn" @click="resetForm">取消</a-button>
          <a-button class="opt-btn" type="primary" @click="handleSubmit">保存</a-button>
        </div>
      </a-form>
    </div>
  </div>
</template>
<script setup>
import { ref, computed, h, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import { message } from "ant-design-vue";
import {
  PlusOutlined,
  MinusCircleOutlined,
  CloudUploadOutlined,
} from "@ant-design/icons-vue";
import edit from "@/components/edit/index.vue";
import API from "@/api/operation";
import systemApi from "@/api/system";


const router = useRouter();
const route = useRoute();
const deviceId = ref(route.query.id); // 修改这里：从params改为query
const isEdit = computed(() => !!deviceId.value);
const formState = ref({
  device_id: "",
  device_status_id: null,
  name: "",
  sn: "",
  warranty_month: null,
  model_number: "",
  app_version: "",
  introduce: "",
  experiments: "",
  remark: "",
  created: "",
  updated: "",
  deleted: false,
  model_files: [],
  image_files: [],
  model_files_list: [],
  image_files_list: [],
  device_param_list: [],
  url_report_repair: ""
});
const resetForm = () => {
  formState.value = {
    device_id: "",
    device_status_id: null,
    name: "",
    sn: "",
    warranty_month: null,
    model_number: "",
    app_version: "",
    introduce: "",
    experiments: "",
    remark: "",
    created: "",
    updated: "",
    deleted: false,
    model_files: [],
    image_files: [],
    model_files_list: [],
    image_files_list: [],
    device_param_list: [],
    url_report_repair: ""
  };
  fileList1.value = [];
  fileList2.value = [];
  router.go(-1);

}
// 状态选项
const statusOptions = ref([
  { value: 0, text: '在售' },
  { value: 1, text: '停售' }
]);
const loading = ref(false);
// 获取设备状态选项（使用固定选项）

// 文件上传相关
const fileList1 = ref([]);
const fileList2 = ref([]);

// 二维码相关

const qrcodeInstance = ref(null);

// 自定义上传函数1 - 设备模型
const customUpload1 = async (options) => {
  const { file, onSuccess, onError } = options;
  try {
    const response = await systemApi.FileUpload(file);
    if (response && response.url) {
      onSuccess(response, file);
    } else {
      onError(new Error('上传失败'));
    }
  } catch (error) {
    console.error('模型文件上传失败:', error);
    onError(error);
  }
};

const handleChange1 = (info) => {
  const status = info.file.status;
  if (status !== "uploading") {
    console.log(info.file, info.fileList);
  }
  if (status === "done") {
    message.success(`${info.file.name} 模型文件上传成功`);
    // 将文件对象添加到 model_files 数组
    if (info.file.response && info.file.response.url) {
      formState.value.model_files.push({
        ...info.file,
        url: info.file.response.url
      });
    }
  } else if (status === "error") {
    message.error(`${info.file.name} 模型文件上传失败`);
  }
};

function handleDrop1(e) {
  console.log('Dropped model files', e.dataTransfer.files);
}

// 自定义上传函数2 - 预览图片
const customUpload2 = async (options) => {
  const { file, onSuccess, onError } = options;
  try {
    const response = await systemApi.FileUpload(file);
    if (response && response.url) {
      onSuccess(response, file);
    } else {
      onError(new Error('上传失败'));
    }
  } catch (error) {
    console.error('图片文件上传失败:', error);
    onError(error);
  }
};

const handleChange2 = (info) => {
  const status = info.file.status;
  if (status !== "uploading") {
    console.log(info.file, info.fileList);
  }
  if (status === "done") {
    message.success(`${info.file.name} 图片文件上传成功`);
    // 将文件对象添加到 image_files 数组
    if (info.file.response && info.file.response.url) {
      formState.value.image_files.push({
        ...info.file,
        url: info.file.response.url
      });
    }
  } else if (status === "error") {
    message.error(`${info.file.name} 图片文件上传失败`);
  }
};

function handleDrop2(e) {
  console.log('Dropped image files', e.dataTransfer.files);
}

// 配置参数管理
const addDevice = () => {
  formState.value.device_param_list.push({
    param_key: "",
    param_value: "",
  });
};

const deleteDevice = (index) => {
  formState.value.device_param_list.splice(index, 1);
};
// 生成二维码
const generateQRCode = (text) => {
  if (qrcodeContainer.value) {
    // 清空之前的二维码
    qrcodeContainer.value.innerHTML = '';

    // 生成新的二维码
    qrcodeInstance.value = new QRCode(qrcodeContainer.value, {
      text: text,
      width: 200,
      height: 200,
      colorDark: '#000000',
      colorLight: '#ffffff',
      correctLevel: QRCode.CorrectLevel.H
    });

    qrcodeText.value = text;
  }
};

// 下载二维码
const downloadQRCode = () => {
  if (qrcodeContainer.value) {
    const canvas = qrcodeContainer.value.querySelector('canvas');
    if (canvas) {
      const link = document.createElement('a');
      link.download = `设备报修二维码_${formState.value.name || formState.value.sn || 'device'}.png`;
      link.href = canvas.toDataURL();
      link.click();
    }
  }
};

// 获取模型文件URL
const getModelFileUrl = () => {
  if (fileList1.value && fileList1.value.length > 0) {
    const file = fileList1.value[0];
    return file.response?.url || file.url || '';
  }
  return '';
};

// 获取图片文件URL
const getImageUrl = () => {
  if (fileList2.value && fileList2.value.length > 0) {
    const file = fileList2.value[0];
    return file.response?.url || file.url || '';
  }
  return '';
};

// 提交表单
const handleSubmit = async () => {
  try {
    if (isEdit.value && deviceId.value) {
      // 编辑模式：使用JSON格式
      const args = {
        device_id: deviceId.value,
        name: formState.value.name,
        sn: formState.value.sn,
        warranty_month: formState.value.warranty_month,
        model_number: formState.value.model_number,
        app_version: formState.value.app_version,
        device_status_id: formState.value.device_status_id,
        introduce: formState.value.introduce,
        experiments: formState.value.experiments,
        remark: formState.value.remark,
        device_param_list: formState.value.device_param_list
      };

      // 添加文件URL（如果有新上传的文件）
      const modelUrl = getModelFileUrl();
      const imageUrl = getImageUrl();
      if (modelUrl) {
        args.model_url = modelUrl;
      }
      if (imageUrl) {
        args.image_url = imageUrl;
      }
      const formData = new FormData();
      formData.append('name', formState.value.name);
      formData.append('device_id', deviceId.value);
      formData.append('sn', formState.value.sn);
      formData.append('warranty_month', formState.value.warranty_month);
      formData.append('model_number', formState.value.model_number);
      formData.append('app_version', formState.value.app_version);
      formData.append('device_status_id', formState.value.device_status_id);
      formData.append('introduce', formState.value.introduce);
      formData.append('experiments', formState.value.experiments);
      formData.append('remark', formState.value.remark);
      formData.append('device_param_list', JSON.stringify(formState.value.device_param_list));
       // 添加模型文件（只上传新选择的文件）
      if (fileList1.value && fileList1.value.length > 0) {
        const modelFile = fileList1.value[0];
        if (modelFile.originFileObj) {
          // 这是新上传的文件
          formData.append('model_files', modelFile.originFileObj);
        }
      }

      // 添加图片文件（只上传新选择的文件）
      if (fileList2.value && fileList2.value.length > 0) {
        const imageFile = fileList2.value[0];
        if (imageFile.originFileObj) {
          // 这是新上传的文件
          formData.append('image_files', imageFile.originFileObj);
        }
      }
      console.log('编辑模式，使用JSON提交', args);
      const res = await API.DeviceEditDeviceArgs(formData);
      console.log('设备更新成功', res);

      message.success('设备更新成功');
      formState.value.device_param_list.forEach(async(item)=>{
        await API.DeviceParamCreate({
          ...item,
          device_id:  res.device_id
        })
      })
    } else {
      // 新增模式：使用FormData格式
      const formData = new FormData();

      // 添加基本字段
      formData.append('name', formState.value.name);
      formData.append('sn', formState.value.sn);
      formData.append('warranty_month', formState.value.warranty_month);
      formData.append('model_number', formState.value.model_number);
      formData.append('app_version', formState.value.app_version);
      formData.append('device_status_id', formState.value.device_status_id);
      formData.append('introduce', formState.value.introduce);
      formData.append('experiments', formState.value.experiments);
      formData.append('remark', formState.value.remark);

      // 添加设备参数列表（JSON字符串）
      formData.append('device_param_list', JSON.stringify(formState.value.device_param_list));

      // 添加模型文件（只上传新选择的文件）
      if (fileList1.value && fileList1.value.length > 0) {
        const modelFile = fileList1.value[0];
        if (modelFile.originFileObj) {
          // 这是新上传的文件
          formData.append('model_files', modelFile.originFileObj);
        }
      }

      // 添加图片文件（只上传新选择的文件）
      if (fileList2.value && fileList2.value.length > 0) {
        const imageFile = fileList2.value[0];
        if (imageFile.originFileObj) {
          // 这是新上传的文件
          formData.append('image_files', imageFile.originFileObj);
        }
      }

      console.log('新增模式，使用FormData提交');
      const response = await API.DeviceCreateDevice(formData);
      console.log('设备创建成功', response);
      message.success('设备创建成功');
      formState.value.device_param_list.forEach(async(item)=>{
        await API.DeviceParamCreate({
          ...item,
          device_id:   response.device_id
        })
      })
    }

    router.back();
  } catch (error) {
    console.error('保存设备失败', error);
    message.error('保存设备失败');
  }
};

const rules = ref({
  name: [
    {
      required: true,
      message: "请输入设备名称",
      trigger: "blur",
    },
  ],
  sn: [
    {
      required: true,
      message: "请输入设备序列号",
      trigger: "blur",
    },
  ],
  model_number: [
    {
      required: true,
      message: "请输入设备型号",
      trigger: "blur",
    },
  ],
  warranty_month: [
    {
      required: true,
      message: "请输入保修期月数",
      trigger: "blur",
    },
  ],
  device_status_id: [
    {
      required: true,
      message: "请选择设备状态",
      trigger: "change",
    },
  ],
});

// 初始化设备参数列表
if (formState.value.device_param_list.length === 0) {
  formState.value.device_param_list.push({
    param_key: "",
    param_value: "",
  });
}

// 页面加载时获取状态选项和设备详情
onMounted(async () => {
  console.log(deviceId.value, 'deviceId')
  if (deviceId.value) {

    getDeviceDetail(deviceId.value);
  }
});
const getDeviceDetail = async (deviceId) => {
  try {
    loading.value = true;
    // 调用DeviceFetchModel接口获取设备详情
    const response = await API.DeviceFetchModel({ device_id: deviceId });
    if (response) {
      const data = response;
      formState.value = {
        device_id: data.device_id || "",
        device_status_id: data.device_status_id !== null && data.device_status_id !== undefined ? Number(data.device_status_id) : null,
        name: data.name || "",
        sn: data.sn || "",
        warranty_month: data.warranty_month || null,
        model_number: data.model_number || "",
        app_version: data.app_version || "",
        introduce: data.introduce || "",
        experiments: data.experiments || "",
        remark: data.remark || "",
        created: data.created || "",
        updated: data.updated || "",
        deleted: data.deleted || false,
        model_files_list: data.model_files_list || [],
        image_files_list: data.image_files_list || [],
        device_param_list: data.device_param_list || [],
        url_report_repair: data.url_report_repair || ""
      };

      // 处理模型文件反显
      if (data.model_files_list && data.model_files_list.length > 0) {
        fileList1.value = data.model_files_list.map((file, index) => ({
          uid: file.fileId || `model-${index}`,
          name: file.file_name || `模型文件${index + 1}`,
          status: 'done',
          url: file.url || '',
          response: {
            url: file.url || ''
          }
        }));
      } else if (data.model_file || data.model_url) {
        // 兼容旧的单文件格式
        fileList1.value = [{
          uid: 'model-1',
          name: data.model_file || '模型文件',
          status: 'done',
          url: data.model_url || '',
          response: {
            url: data.model_url || ''
          }
        }];
      }

      // 处理图片文件反显
      if (data.image_files_list && data.image_files_list.length > 0) {
        fileList2.value = data.image_files_list.map((file, index) => ({
          uid: file.fileId || `image-${index}`,
          name: file.file_name || `预览图片${index + 1}`,
          status: 'done',
          url: file.url || '',
          response: {
            url: file.url || ''
          }
        }));
      } else if (data.image || data.thumb_url) {
        // 兼容旧的单文件格式
        fileList2.value = [{
          uid: 'image-1',
          name: data.image || '预览图片',
          status: 'done',
          url: data.thumb_url || '',
          response: {
            url: data.thumb_url || ''
          }
        }];
      }
    } else {
      message.error('获取设备详情失败');
    }
  } catch (error) {
    console.error('获取设备详情失败:', error);
    message.error('获取设备详情失败');
  } finally {
    loading.value = false;
  }
};


</script>
